/**
 * (created at 2011-2-18)
 */
package qiushuo.mysqlparser.recognizer.dispatcher;

import static qiushuo.mysqlparser.recognizer.SQLTokenType.IDENTIFIER;

import java.sql.SQLSyntaxErrorException;

import qiushuo.mysqlparser.ast.statement.Statement.StmtType;
import qiushuo.mysqlparser.recognizer.CharReader;
import qiushuo.mysqlparser.recognizer.SQLLexer;
import qiushuo.mysqlparser.recognizer.SQLToken;
import qiushuo.mysqlparser.recognizer.TokenReader;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class ParserDispatcher {
    public static StmtType determineStmtType(String sql) throws SQLSyntaxErrorException {
        SQLLexer lexer = new SQLLexer(new CharReader(sql));
        TokenReader input = new TokenReader(lexer);
        SQLToken token = input.next();
        if (token == null) {
            throw new SQLSyntaxErrorException("unexpected token type");
        }
        switch (token.getType()) {
        case KW_SET:
            if (input.isNext(IDENTIFIER, 0, true, "TRANSACTION") || input.isNext(IDENTIFIER, 1, true, "TRANSACTION")) {
                input.backForce();
                return StmtType.MTL_ISOLATION;
            }
            input.backForce();
            return StmtType.DAL_SET;
        case KW_SHOW:
            input.backForce();
            return StmtType.DAL_SHOW;
        case KW_UPDATE:
            input.backForce();
            return StmtType.DML_UPDATE;
        case KW_SELECT:
        case PUNC_LEFT_PAREN:
            input.backForce();
            return StmtType.DML_SELECT;
        case KW_REPLACE:
            input.backForce();
            return StmtType.DML_REPLACE;
        case KW_INSERT:
            input.backForce();
            return StmtType.DML_INSERT;
        case KW_DELETE:
            input.backForce();
            return StmtType.DML_DELETE;
        case KW_CALL:
            input.backForce();
            return StmtType.DML_CALL;
        case IDENTIFIER:
            String text = token.getText().toUpperCase();
            if ("START".equals(text)) {
                input.backForce();
                return StmtType.MTL_START;
            } else if ("ROLLBACK".equals(text) || "COMMIT".equals(text)) {
                input.backForce();
                return StmtType.MTL_TERMINATE;
            }
        default:
            throw new IllegalArgumentException("undetermined sql: " + sql);
        }

    }
}
